<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Spring Security &amp; Oauth2 | 海内存知已，天涯若比邻</title><meta name="keywords" content="Java,Security,Oauth2"><meta name="author" content="mowei"><meta name="copyright" content="mowei"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="一、Spring Security1、xml依赖1234&lt;dependency&gt;    &lt;groupId&gt;org.springframework.boot&lt;&#x2F;groupId&gt;    &lt;artifactId&gt;spring-boot-starter-security&lt;&#x2F;artifactId&gt;&lt;&#x2F;dependency&gt; 2、yml配">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring Security &amp; Oauth2">
<meta property="og:url" content="https://gitee.com/momomomowei/blog/java/01%20Spring%20Security%20&%20oauth2/index.html">
<meta property="og:site_name" content="海内存知已，天涯若比邻">
<meta property="og:description" content="一、Spring Security1、xml依赖1234&lt;dependency&gt;    &lt;groupId&gt;org.springframework.boot&lt;&#x2F;groupId&gt;    &lt;artifactId&gt;spring-boot-starter-security&lt;&#x2F;artifactId&gt;&lt;&#x2F;dependency&gt; 2、yml配">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/momomomowei/images/spring-security.jpeg">
<meta property="article:published_time" content="2024-04-25T07:24:45.000Z">
<meta property="article:modified_time" content="2024-04-21T07:24:14.367Z">
<meta property="article:author" content="mowei">
<meta property="article:tag" content="Java">
<meta property="article:tag" content="Security">
<meta property="article:tag" content="Oauth2">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/momomomowei/images/spring-security.jpeg"><link rel="shortcut icon" href="/media/favicon.png"><link rel="canonical" href="https://gitee.com/momomomowei/blog/java/01%20Spring%20Security%20&amp;%20oauth2/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: true,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Spring Security & Oauth2',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2024-04-21 15:24:14'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    document.addEventListener('pjax:complete', detectApple)})(window)</script><meta name="generator" content="Hexo 5.4.2"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="/media/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">41</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">29</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">7</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 目录</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/images/spring-security.jpeg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">海内存知已，天涯若比邻</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 目录</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Spring Security &amp; Oauth2</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2024-04-25T07:24:45.000Z" title="发表于 2024-04-25 15:24:45">2024-04-25</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2024-04-21T07:24:14.367Z" title="更新于 2024-04-21 15:24:14">2024-04-21</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Java/">Java</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">5.9k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>29分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Spring Security &amp; Oauth2"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="一、Spring-Security"><a href="#一、Spring-Security" class="headerlink" title="一、Spring Security"></a>一、Spring Security</h1><h2 id="1、xml依赖"><a href="#1、xml依赖" class="headerlink" title="1、xml依赖"></a>1、xml依赖</h2><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-security<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h2 id="2、yml配置"><a href="#2、yml配置" class="headerlink" title="2、yml配置"></a>2、yml配置</h2><figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 应用名称</span></span><br><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">application:</span></span><br><span class="line">    <span class="attr">name:</span> <span class="string">security-demo</span></span><br><span class="line">  <span class="comment"># 配置的用户密码，如果在WebSecurityConfigurerAdapter中配置， 这个会失效</span></span><br><span class="line">  <span class="comment">#security:</span></span><br><span class="line">  <span class="comment">#  user:</span></span><br><span class="line">  <span class="comment">#    name: admin</span></span><br><span class="line">  <span class="comment">#    password: admin</span></span><br><span class="line"></span><br><span class="line"><span class="attr">server:</span></span><br><span class="line">  <span class="attr">port:</span> <span class="number">9999</span></span><br></pre></td></tr></table></figure>
<h2 id="3、Security配置"><a href="#3、Security配置" class="headerlink" title="3、Security配置"></a>3、Security配置</h2><blockquote>
<p>如果要定义403页面，需要放在<code>resource/static/error/403.html</code></p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">WebSecurityConfiguration</span> <span class="keyword">extends</span> <span class="title class_">WebSecurityConfigurerAdapter</span> &#123;</span><br><span class="line">    <span class="comment">// 登录成功之后的处理器</span></span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    AuthenticationSuccessHandler authenticationSuccessHandler;</span><br><span class="line">    <span class="comment">// 访问被拒的处理器</span></span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    AccessDeniedHandler accessDeniedHandler;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 必须要放一个密码加密器</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> PasswordEncoder <span class="title function_">passwordEncoder</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">BCryptPasswordEncoder</span>();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 配置登录缓存方式和账号密码</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(AuthenticationManagerBuilder auth)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        auth.inMemoryAuthentication()</span><br><span class="line">                <span class="comment">/**</span></span><br><span class="line"><span class="comment">                 * 设置一个用户</span></span><br><span class="line"><span class="comment">                 *  roles 代表角色</span></span><br><span class="line"><span class="comment">                 *  authorities 代表拥有的权限列表（自己定义的），一旦设置了权限，角色就失效了</span></span><br><span class="line"><span class="comment">                 */</span></span><br><span class="line">                .withUser(<span class="string">&quot;admin&quot;</span>)</span><br><span class="line">                .password(passwordEncoder().encode(<span class="string">&quot;admin&quot;</span>))</span><br><span class="line">                .roles(<span class="string">&quot;ADMIN&quot;</span>)</span><br><span class="line">                .authorities(<span class="string">&quot;sys:add&quot;</span>,<span class="string">&quot;sys:delete&quot;</span>,<span class="string">&quot;sys:update&quot;</span>,<span class="string">&quot;sys:select&quot;</span>)</span><br><span class="line"></span><br><span class="line">                .and()</span><br><span class="line">                .withUser(<span class="string">&quot;test&quot;</span>)</span><br><span class="line">                .password(passwordEncoder().encode(<span class="string">&quot;test&quot;</span>))</span><br><span class="line">                .roles(<span class="string">&quot;TEST&quot;</span>)</span><br><span class="line">                .authorities(<span class="string">&quot;sys:select&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     *  配置登录，授权详细分配（入门）</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(HttpSecurity http)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="comment">// 定义访问被拒的处理器，配置了这个自定义403页面失效</span></span><br><span class="line">        http</span><br><span class="line">                .exceptionHandling()</span><br><span class="line">                .accessDeniedHandler(accessDeniedHandler);</span><br><span class="line">        </span><br><span class="line">        </span><br><span class="line">        http    <span class="comment">// formLogin 给一个登录表单</span></span><br><span class="line">                .formLogin()</span><br><span class="line">            	<span class="comment">// successForwardUrl 登录成功走的接口</span></span><br><span class="line">                <span class="comment">// .successForwardUrl(&quot;/login-success&quot;)</span></span><br><span class="line">            	<span class="comment">// 配置登录成功之后的处理器，如果配置了这个successForwardUrl会失效</span></span><br><span class="line">                .successHandler(authenticationSuccessHandler)</span><br><span class="line">            </span><br><span class="line">                <span class="comment">// failureForwardUrl 定义登录失败走的接口</span></span><br><span class="line">                <span class="comment">// .failureForwardUrl(&quot;/login-fail&quot;)</span></span><br><span class="line">            	<span class="comment">// 配置登录失败处理器，配置这个failureForwardUrl失效</span></span><br><span class="line">                .failureHandler(authenticationFailureHandler())</span><br><span class="line">                <span class="comment">// permitAll 代表放行</span></span><br><span class="line">                .permitAll()</span><br><span class="line"></span><br><span class="line">                <span class="comment">//.and()</span></span><br><span class="line">                <span class="comment">//.authorizeRequests()</span></span><br><span class="line">                <span class="comment">// antMatchers 匹配接口需要的权限（测试写法，有更好的替换）</span></span><br><span class="line">                <span class="comment">//.antMatchers(&quot;/add&quot;).hasAuthority(&quot;sys:add&quot;)</span></span><br><span class="line">                <span class="comment">//.antMatchers(&quot;/delete&quot;).hasAuthority(&quot;sys:delete&quot;)</span></span><br><span class="line">            	<span class="comment">//.antMatchers(&quot;/update/**&quot;).hasRole(&quot;ADMIN&quot;)</span></span><br><span class="line">            	<span class="comment">//.antMatchers(&quot;/select&quot;).hasRole(&quot;TEST&quot;)</span></span><br><span class="line"></span><br><span class="line">                <span class="comment">// 除了上面放行的，其他都要登录才能访问，注意要放在最后！！</span></span><br><span class="line">                .and()</span><br><span class="line">                .authorizeRequests()</span><br><span class="line">                .anyRequest()</span><br><span class="line">                .authenticated();</span><br><span class="line">     &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="4、获取用户信息"><a href="#4、获取用户信息" class="headerlink" title="4、获取用户信息"></a>4、获取用户信息</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> org.springframework.security.core.Authentication;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.core.context.SecurityContextHolder;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.GetMapping;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.RestController;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.security.Principal;</span><br><span class="line"></span><br><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">UserController</span> &#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     *  方式1：</span></span><br><span class="line"><span class="comment">     *  通过 Principal 获取</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@GetMapping(&quot;/getUserInfo&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> Object <span class="title function_">getUserInfo</span><span class="params">(Principal principal)</span> &#123;</span><br><span class="line">        System.out.println(principal);</span><br><span class="line">        <span class="keyword">return</span> principal;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     *  方式2：</span></span><br><span class="line"><span class="comment">     *  当登录完以后，会把用户信息放在 SecurityContextHolder 里面去，这种是基于session方式的认证</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@GetMapping(&quot;/getUserInfo2&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> Object <span class="title function_">getUserInfo2</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">Authentication</span> <span class="variable">authentication</span> <span class="operator">=</span> SecurityContextHolder.getContext().getAuthentication();</span><br><span class="line">        <span class="keyword">return</span> authentication;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>结果示例：</strong></p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="punctuation">&#123;</span></span><br><span class="line">    <span class="attr">&quot;authorities&quot;</span><span class="punctuation">:</span> <span class="punctuation">[</span></span><br><span class="line">        <span class="punctuation">&#123;</span></span><br><span class="line">            <span class="attr">&quot;authority&quot;</span><span class="punctuation">:</span> <span class="string">&quot;ROLE_TEST&quot;</span></span><br><span class="line">        <span class="punctuation">&#125;</span></span><br><span class="line">    <span class="punctuation">]</span><span class="punctuation">,</span></span><br><span class="line">    <span class="attr">&quot;details&quot;</span><span class="punctuation">:</span> <span class="punctuation">&#123;</span></span><br><span class="line">        <span class="attr">&quot;remoteAddress&quot;</span><span class="punctuation">:</span> <span class="string">&quot;0:0:0:0:0:0:0:1&quot;</span><span class="punctuation">,</span></span><br><span class="line">        <span class="attr">&quot;sessionId&quot;</span><span class="punctuation">:</span> <span class="string">&quot;1DC71C296187BB43EB31B2C0CE361050&quot;</span></span><br><span class="line">    <span class="punctuation">&#125;</span><span class="punctuation">,</span></span><br><span class="line">    <span class="attr">&quot;authenticated&quot;</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">true</span></span><span class="punctuation">,</span></span><br><span class="line">    <span class="attr">&quot;principal&quot;</span><span class="punctuation">:</span> <span class="punctuation">&#123;</span></span><br><span class="line">        <span class="attr">&quot;password&quot;</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">null</span></span><span class="punctuation">,</span></span><br><span class="line">        <span class="attr">&quot;username&quot;</span><span class="punctuation">:</span> <span class="string">&quot;test&quot;</span><span class="punctuation">,</span></span><br><span class="line">        <span class="attr">&quot;authorities&quot;</span><span class="punctuation">:</span> <span class="punctuation">[</span></span><br><span class="line">            <span class="punctuation">&#123;</span></span><br><span class="line">                <span class="attr">&quot;authority&quot;</span><span class="punctuation">:</span> <span class="string">&quot;ROLE_TEST&quot;</span></span><br><span class="line">            <span class="punctuation">&#125;</span></span><br><span class="line">        <span class="punctuation">]</span><span class="punctuation">,</span></span><br><span class="line">        <span class="attr">&quot;accountNonExpired&quot;</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">true</span></span><span class="punctuation">,</span></span><br><span class="line">        <span class="attr">&quot;accountNonLocked&quot;</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">true</span></span><span class="punctuation">,</span></span><br><span class="line">        <span class="attr">&quot;credentialsNonExpired&quot;</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">true</span></span><span class="punctuation">,</span></span><br><span class="line">        <span class="attr">&quot;enabled&quot;</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">true</span></span></span><br><span class="line">    <span class="punctuation">&#125;</span><span class="punctuation">,</span></span><br><span class="line">    <span class="attr">&quot;credentials&quot;</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">null</span></span><span class="punctuation">,</span></span><br><span class="line">    <span class="attr">&quot;name&quot;</span><span class="punctuation">:</span> <span class="string">&quot;test&quot;</span></span><br><span class="line"><span class="punctuation">&#125;</span></span><br></pre></td></tr></table></figure>
<h2 id="5、自定义登录成功Handler"><a href="#5、自定义登录成功Handler" class="headerlink" title="5、自定义登录成功Handler"></a>5、自定义登录成功Handler</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.fasterxml.jackson.databind.ObjectMapper;</span><br><span class="line"><span class="keyword">import</span> lombok.extern.slf4j.Slf4j;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Configuration;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.core.Authentication;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.web.authentication.AuthenticationSuccessHandler;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.servlet.ServletException;</span><br><span class="line"><span class="keyword">import</span> javax.servlet.http.HttpServletRequest;</span><br><span class="line"><span class="keyword">import</span> javax.servlet.http.HttpServletResponse;</span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.io.PrintWriter;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> *  登录成功之后执行的处理器</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Slf4j</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MySuccessConfiguration</span> <span class="keyword">implements</span> <span class="title class_">AuthenticationSuccessHandler</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">onAuthenticationSuccess</span><span class="params">(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication)</span> <span class="keyword">throws</span> IOException, ServletException &#123;</span><br><span class="line">        log.info(<span class="string">&quot;==============登录成功了==================&quot;</span>);</span><br><span class="line">        httpServletResponse.setContentType(<span class="string">&quot;application/json;charset=utf-8&quot;</span>);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 转换成json</span></span><br><span class="line">        <span class="type">ObjectMapper</span> <span class="variable">mapper</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ObjectMapper</span>();</span><br><span class="line">        <span class="type">String</span> <span class="variable">result</span> <span class="operator">=</span> mapper.writeValueAsString(authentication);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 写出数据</span></span><br><span class="line">        <span class="type">PrintWriter</span> <span class="variable">writer</span> <span class="operator">=</span> httpServletResponse.getWriter();</span><br><span class="line">        writer.write(result);</span><br><span class="line">        writer.flush();</span><br><span class="line">        writer.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="6、自定义登录失败Handler"><a href="#6、自定义登录失败Handler" class="headerlink" title="6、自定义登录失败Handler"></a>6、自定义登录失败Handler</h2><blockquote>
<p>采用lambda写法，也可以同上面<code>登录成功之后执行的处理器</code>一样的写法， </p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">WebSecurityConfiguration</span> <span class="keyword">extends</span> <span class="title class_">WebSecurityConfigurerAdapter</span> &#123;</span><br><span class="line">    .....</span><br><span class="line">        </span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 登录失败之后的处理器（lambda写法）</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> AuthenticationFailureHandler <span class="title function_">authenticationFailureHandler</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> (request, response, exception) -&gt; &#123;</span><br><span class="line">            log.info(<span class="string">&quot;==============登录失败了==================&quot;</span>);</span><br><span class="line">            response.setContentType(<span class="string">&quot;application/json;charset=utf-8&quot;</span>);</span><br><span class="line"></span><br><span class="line">            String msg;</span><br><span class="line">            <span class="keyword">if</span> (exception <span class="keyword">instanceof</span> LockedException) &#123;</span><br><span class="line">                msg = <span class="string">&quot;账号被锁定&quot;</span>;</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (exception <span class="keyword">instanceof</span> BadCredentialsException) &#123;</span><br><span class="line">                msg = <span class="string">&quot;账号或密码错误&quot;</span>;</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (exception <span class="keyword">instanceof</span> DisabledException) &#123;</span><br><span class="line">                msg = <span class="string">&quot;账号被禁用&quot;</span>;</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (exception <span class="keyword">instanceof</span> AccountExpiredException) &#123;</span><br><span class="line">                msg = <span class="string">&quot;账号已过期&quot;</span>;</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (exception <span class="keyword">instanceof</span> CredentialsExpiredException) &#123;</span><br><span class="line">                msg = <span class="string">&quot;密码已过期&quot;</span>;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                msg = <span class="string">&quot;登录失败！&quot;</span>;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 转换成json</span></span><br><span class="line">            <span class="type">ObjectMapper</span> <span class="variable">mapper</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ObjectMapper</span>();</span><br><span class="line">            <span class="type">String</span> <span class="variable">result</span> <span class="operator">=</span> mapper.writeValueAsString(msg);</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 写出数据</span></span><br><span class="line">            <span class="type">PrintWriter</span> <span class="variable">writer</span> <span class="operator">=</span> response.getWriter();</span><br><span class="line">            writer.write(result);</span><br><span class="line">            writer.flush();</span><br><span class="line">            writer.close();</span><br><span class="line">        &#125;;</span><br><span class="line">    &#125;</span><br><span class="line">        </span><br><span class="line">    .....</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="7、自定义访问被拒Handler"><a href="#7、自定义访问被拒Handler" class="headerlink" title="7、自定义访问被拒Handler"></a>7、自定义访问被拒Handler</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.fasterxml.jackson.databind.ObjectMapper;</span><br><span class="line"><span class="keyword">import</span> lombok.extern.slf4j.Slf4j;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Configuration;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.access.AccessDeniedException;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.web.access.AccessDeniedHandler;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.servlet.ServletException;</span><br><span class="line"><span class="keyword">import</span> javax.servlet.http.HttpServletRequest;</span><br><span class="line"><span class="keyword">import</span> javax.servlet.http.HttpServletResponse;</span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.io.PrintWriter;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Slf4j</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MyAccessDeniedHandler</span> <span class="keyword">implements</span> <span class="title class_">AccessDeniedHandler</span> &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">handle</span><span class="params">(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        log.info(<span class="string">&quot;==============访问被拒了==================&quot;</span>);</span><br><span class="line">        response.setContentType(<span class="string">&quot;application/json;charset=utf-8&quot;</span>);</span><br><span class="line">        <span class="comment">// 转换成json</span></span><br><span class="line">        <span class="type">ObjectMapper</span> <span class="variable">mapper</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ObjectMapper</span>();</span><br><span class="line">        <span class="type">String</span> <span class="variable">result</span> <span class="operator">=</span> mapper.writeValueAsString(accessDeniedException.getMessage());</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 写出数据</span></span><br><span class="line">        <span class="type">PrintWriter</span> <span class="variable">writer</span> <span class="operator">=</span> response.getWriter();</span><br><span class="line">        writer.write(result);</span><br><span class="line">        writer.flush();</span><br><span class="line">        writer.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="8、方法级别的权限控制"><a href="#8、方法级别的权限控制" class="headerlink" title="8、方法级别的权限控制"></a>8、方法级别的权限控制</h2><h3 id="8-1主启动类添加注解"><a href="#8-1主启动类添加注解" class="headerlink" title="8.1主启动类添加注解"></a>8.1主启动类添加注解</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@SpringBootApplication</span></span><br><span class="line"><span class="comment">// 开启方法级别的认证</span></span><br><span class="line"><span class="meta">@EnableGlobalMethodSecurity(prePostEnabled = true)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">SecurityDemoApplication</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        SpringApplication.run(SecurityDemoApplication.class, args);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="8-2方法级别验证"><a href="#8-2方法级别验证" class="headerlink" title="8.2方法级别验证"></a>8.2方法级别验证</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">AuthenticateTestController</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping(&quot;/delete&quot;)</span></span><br><span class="line">    <span class="meta">@PreAuthorize(&quot;hasRole(&#x27;ADMIN&#x27;)&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">delete</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;delete&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping(&quot;/add&quot;)</span></span><br><span class="line">    <span class="meta">@PreAuthorize(&quot;hasAuthority(&#x27;sys:delete&#x27;)&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">add</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;add&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="9、自定义用户登录"><a href="#9、自定义用户登录" class="headerlink" title="9、自定义用户登录"></a>9、自定义用户登录</h2><h3 id="9-1实现UserDetailsService接口"><a href="#9-1实现UserDetailsService接口" class="headerlink" title="9.1实现UserDetailsService接口"></a>9.1实现UserDetailsService接口</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> org.springframework.security.core.authority.SimpleGrantedAuthority;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.core.userdetails.User;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.core.userdetails.UserDetails;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.core.userdetails.UserDetailsService;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.core.userdetails.UsernameNotFoundException;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.crypto.password.PasswordEncoder;</span><br><span class="line"><span class="keyword">import</span> org.springframework.stereotype.Service;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.context.request.RequestContextHolder;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.context.request.ServletRequestAttributes;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.annotation.Resource;</span><br><span class="line"><span class="keyword">import</span> javax.servlet.http.HttpServletRequest;</span><br><span class="line"><span class="keyword">import</span> java.util.ArrayList;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 自定义登录</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Service</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">UserDetailServiceImpl</span> <span class="keyword">implements</span> <span class="title class_">UserDetailsService</span> &#123;</span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    <span class="keyword">private</span> PasswordEncoder passwordEncoder;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 可以在此处继承数据来查询用户的账号，密码，权限等</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> UserDetails <span class="title function_">loadUserByUsername</span><span class="params">(String username)</span> <span class="keyword">throws</span> UsernameNotFoundException &#123;</span><br><span class="line">        <span class="comment">// 如何获取请求信息</span></span><br><span class="line">        <span class="type">ServletRequestAttributes</span> <span class="variable">requestAttributes</span> <span class="operator">=</span> (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();</span><br><span class="line">        HttpServletRequest request;</span><br><span class="line">        <span class="keyword">if</span> (requestAttributes != <span class="literal">null</span>) &#123;</span><br><span class="line">            request = requestAttributes.getRequest();</span><br><span class="line">            <span class="type">String</span> <span class="variable">header</span> <span class="operator">=</span> request.getHeader(<span class="string">&quot;Authorization&quot;</span>);</span><br><span class="line">            System.out.println(header);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 模拟一个用户，真实应该继承数据库查询获得</span></span><br><span class="line">        ArrayList&lt;SimpleGrantedAuthority&gt; adminAuthorities = <span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;&gt;();</span><br><span class="line">        adminAuthorities.add(<span class="keyword">new</span> <span class="title class_">SimpleGrantedAuthority</span>(<span class="string">&quot;sys:add&quot;</span>));</span><br><span class="line">        adminAuthorities.add(<span class="keyword">new</span> <span class="title class_">SimpleGrantedAuthority</span>(<span class="string">&quot;sys:delete&quot;</span>));</span><br><span class="line">        adminAuthorities.add(<span class="keyword">new</span> <span class="title class_">SimpleGrantedAuthority</span>(<span class="string">&quot;sys:update&quot;</span>));</span><br><span class="line">        adminAuthorities.add(<span class="keyword">new</span> <span class="title class_">SimpleGrantedAuthority</span>(<span class="string">&quot;sys:select&quot;</span>));</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">User</span>(<span class="string">&quot;admin&quot;</span>, passwordEncoder.encode(<span class="string">&quot;admin&quot;</span>), adminAuthorities);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="9-2配置WebSecurityConfigurerAdapter继承类"><a href="#9-2配置WebSecurityConfigurerAdapter继承类" class="headerlink" title="9.2配置WebSecurityConfigurerAdapter继承类"></a>9.2配置WebSecurityConfigurerAdapter继承类</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">WebSecurityConfiguration</span> <span class="keyword">extends</span> <span class="title class_">WebSecurityConfigurerAdapter</span> &#123;</span><br><span class="line">    ............</span><br><span class="line">    </span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    <span class="keyword">private</span> UserDetailServiceImpl userDetailService;</span><br><span class="line">    </span><br><span class="line">    </span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 配置用户和权限</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(AuthenticationManagerBuilder auth)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">		<span class="comment">//        auth.inMemoryAuthentication()</span></span><br><span class="line">		<span class="comment">//                .withUser(&quot;admin&quot;)</span></span><br><span class="line">		<span class="comment">//                .password(passwordEncoder.encode(&quot;admin&quot;))</span></span><br><span class="line">		<span class="comment">//                .roles(&quot;ADMIN&quot;)</span></span><br><span class="line">		<span class="comment">//                .authorities(&quot;sys:add&quot;, &quot;sys:delete&quot;, &quot;sys:update&quot;, &quot;sys:select&quot;)；</span></span><br><span class="line">        auth.userDetailsService(userDetailService);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<h2 id="10、记住我"><a href="#10、记住我" class="headerlink" title="10、记住我"></a>10、记住我</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">WebSecurityConfiguration</span> <span class="keyword">extends</span> <span class="title class_">WebSecurityConfigurerAdapter</span> &#123;</span><br><span class="line">    ......</span><br><span class="line">        </span><br><span class="line">        </span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 配置登录，授权详细分配（入门）</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(HttpSecurity http)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="comment">// 定义登录被拒handler</span></span><br><span class="line">        http</span><br><span class="line">                .exceptionHandling()</span><br><span class="line">                .accessDeniedHandler(accessDeniedHandler);</span><br><span class="line"></span><br><span class="line">        http</span><br><span class="line">           		.......</span><br><span class="line"></span><br><span class="line">                <span class="comment">// 记住我功能实现，rememberMeParameter表示 input 标签 name 属性</span></span><br><span class="line">                .and()</span><br><span class="line">                .rememberMe()</span><br><span class="line">                .rememberMeParameter(<span class="string">&quot;remember-me&quot;</span>)</span><br><span class="line">                .tokenRepository(persistentTokenRepository())</span><br><span class="line"></span><br><span class="line">            	.........</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 记住我功能数据库</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> PersistentTokenRepository <span class="title function_">persistentTokenRepository</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">JdbcTokenRepositoryImpl</span> <span class="variable">tokenRepository</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">JdbcTokenRepositoryImpl</span>();</span><br><span class="line">        tokenRepository.setCreateTableOnStartup(<span class="literal">true</span>);</span><br><span class="line">        <span class="keyword">return</span> tokenRepository;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    ...........</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="二、oauth2"><a href="#二、oauth2" class="headerlink" title="二、oauth2"></a>二、oauth2</h1><p><a target="_blank" rel="noopener" href="http://localhost:9999/oauth/authorize?response_type=code&amp;client_id=wx&amp;state=momo&amp;redirect_uri=https://www.baidu.com">http://localhost:9999/oauth/authorize?response_type=code&amp;client_id=wx&amp;state=momo&amp;redirect_uri=https://www.baidu.com</a></p>
<h2 id="1、xml依赖-1"><a href="#1、xml依赖-1" class="headerlink" title="1、xml依赖"></a>1、xml依赖</h2><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.cloud<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-cloud-starter-oauth2<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.2.5.RELEASE<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h2 id="2、yml配置-1"><a href="#2、yml配置-1" class="headerlink" title="2、yml配置"></a>2、yml配置</h2><figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">server:</span></span><br><span class="line">  <span class="attr">port:</span> <span class="number">9999</span></span><br><span class="line"></span><br><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">application:</span></span><br><span class="line">    <span class="attr">name:</span> <span class="string">momo-oauth2-server</span></span><br><span class="line"></span><br><span class="line">  <span class="attr">cloud:</span></span><br><span class="line">    <span class="attr">nacos:</span></span><br><span class="line">      <span class="attr">discovery:</span></span><br><span class="line">        <span class="attr">server-addr:</span> <span class="string">$&#123;NACOS-HOST:182.61.55.41&#125;:$&#123;NACOS-PORT:8848&#125;</span></span><br><span class="line"></span><br><span class="line">  <span class="attr">redis:</span></span><br><span class="line">    <span class="attr">host:</span> <span class="number">182.61</span><span class="number">.55</span><span class="number">.41</span></span><br><span class="line">    <span class="attr">port:</span> <span class="number">6379</span></span><br><span class="line">    <span class="attr">password:</span> <span class="string">momo123456...</span></span><br><span class="line">    <span class="attr">database:</span> <span class="number">0</span></span><br><span class="line">    <span class="attr">timeout:</span> <span class="number">10000</span></span><br></pre></td></tr></table></figure>
<h2 id="3、主启动类"><a href="#3、主启动类" class="headerlink" title="3、主启动类"></a>3、主启动类</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@SpringBootApplication</span></span><br><span class="line"><span class="meta">@EnableAuthorizationServer</span> <span class="comment">// 标识为授权服务器</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MomoOauth2Application</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        SpringApplication.run(MomoOauth2Application.class, args);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="4、配置Security"><a href="#4、配置Security" class="headerlink" title="4、配置Security"></a>4、配置Security</h2><h3 id="4-1公用的bean配置"><a href="#4-1公用的bean配置" class="headerlink" title="4.1公用的bean配置"></a>4.1公用的bean配置</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 配置公用的bean</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">SecurityOauth2Config</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> PasswordEncoder <span class="title function_">passwordEncoder</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">BCryptPasswordEncoder</span>();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="4-2Security配置"><a href="#4-2Security配置" class="headerlink" title="4.2Security配置"></a>4.2Security配置</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Bean;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Configuration;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.authentication.AuthenticationManager;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.config.annotation.web.builders.HttpSecurity;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.crypto.password.PasswordEncoder;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.annotation.Resource;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 配置Security</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">WebSecurityConfiguration</span> <span class="keyword">extends</span> <span class="title class_">WebSecurityConfigurerAdapter</span> &#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 密码加密器</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    <span class="keyword">private</span> PasswordEncoder passwordEncoder;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 配置用户和权限</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(AuthenticationManagerBuilder auth)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        auth.inMemoryAuthentication()</span><br><span class="line">                .withUser(<span class="string">&quot;admin&quot;</span>)</span><br><span class="line">                .password(passwordEncoder.encode(<span class="string">&quot;admin&quot;</span>))</span><br><span class="line">                .roles(<span class="string">&quot;ADMIN&quot;</span>)</span><br><span class="line">                .authorities(<span class="string">&quot;sys:add&quot;</span>, <span class="string">&quot;sys:delete&quot;</span>, <span class="string">&quot;sys:update&quot;</span>, <span class="string">&quot;sys:select&quot;</span>)</span><br><span class="line"></span><br><span class="line">                .and()</span><br><span class="line">                .withUser(<span class="string">&quot;test&quot;</span>)</span><br><span class="line">                .password(passwordEncoder.encode(<span class="string">&quot;test&quot;</span>))</span><br><span class="line">                .roles(<span class="string">&quot;TEST&quot;</span>)</span><br><span class="line">                .authorities(<span class="string">&quot;sys:select&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 配置登录，请求权限等</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(HttpSecurity http)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="comment">// 关闭跨站请求伪造功能</span></span><br><span class="line">        http.csrf().disable();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 给一个登录表单</span></span><br><span class="line">        http.formLogin();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 配置所有请求都需要授权才能访问</span></span><br><span class="line">        http.authorizeRequests().anyRequest().authenticated();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     *  如果使用password授权模式，需要在容器里面放一个 AuthenticationManager</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="comment">// @Override</span></span><br><span class="line">    <span class="comment">// @Bean</span></span><br><span class="line">    <span class="comment">// protected AuthenticationManager authenticationManager() throws Exception &#123;</span></span><br><span class="line">    <span class="comment">//     return super.authenticationManager();</span></span><br><span class="line">    <span class="comment">// &#125;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="5、Oauth2配置"><a href="#5、Oauth2配置" class="headerlink" title="5、Oauth2配置"></a>5、Oauth2配置</h2><blockquote>
<ul>
<li>一，oauth2共4种授权模式：<ul>
<li>1.code码授权 authorization_code</li>
<li>2.静默授权 implicit</li>
<li>3.密码授权 password</li>
<li>4.客户端授权 client_credentials</li>
</ul>
</li>
<li>二，需要先配置Security的登录，然后才能访问授权接口</li>
</ul>
</blockquote>
<h3 id="5-1code授权"><a href="#5-1code授权" class="headerlink" title="5.1code授权"></a>5.1code授权</h3><ul>
<li>请求示例：<a target="_blank" rel="noopener" href="http://localhost:9999/oauth/authorize?response_type=code&amp;client_id=wx&amp;redirect_uri=https://www.baidu.com&amp;state=momo">http://localhost:9999/oauth/authorize?response_type=code&amp;client_id=wx&amp;redirect_uri=https://www.baidu.com&amp;state=momo</a><ol>
<li>选跳转到登录页面，登录成功后授权，然后会得到类似的结果：<a target="_blank" rel="noopener" href="https://www.baidu.com/?code=5Y4dow&amp;state=momo">https://www.baidu.com/?code=5Y4dow&amp;state=momo</a></li>
<li>再发送请求获取token，示例：<a target="_blank" rel="noopener" href="http://localhost:9999/oauth/token?grant_type=authorization_code&amp;redirect_uri=https://www.baidu.com&amp;code=5Y4dow，`需要在Authorization中选Basic">http://localhost:9999/oauth/token?grant_type=authorization_code&amp;redirect_uri=https://www.baidu.com&amp;code=5Y4dow，`需要在Authorization中选Basic</a> Auth ，值为下面配置的客户端账号`，（原理是加一个请求头，key为Authorization，value为”Basic 客户端账号:客户端密码”的base64）</li>
</ol>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Bean;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Configuration;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.redis.connection.RedisConnectionFactory;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.authentication.AuthenticationManager;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.crypto.password.PasswordEncoder;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.oauth2.provider.token.TokenStore;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.annotation.Resource;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">AuthorizationServerConfiguration</span> <span class="keyword">extends</span> <span class="title class_">AuthorizationServerConfigurerAdapter</span> &#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 密码加密器</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    <span class="keyword">private</span> PasswordEncoder passwordEncoder;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Redis的连接工厂，用于oauth保存信息（自动保存的，给个工厂就行）</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    <span class="keyword">private</span> RedisConnectionFactory redisConnectionFactory;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 用于oauth保存信息（自动保存）</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> TokenStore <span class="title function_">tokenStore</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">RedisTokenStore</span>(redisConnectionFactory);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 客户端配置，可配置多个</span></span><br><span class="line"><span class="comment">     * withClient：客户端名称</span></span><br><span class="line"><span class="comment">     * secret：客户端密钥，注意要用使用PasswordEncoder加密</span></span><br><span class="line"><span class="comment">     * scopes：客户端作作用域（理解成权限列表，用户自定义的）</span></span><br><span class="line"><span class="comment">     * authorizedGrantTypes：授权模式，可以配置多种</span></span><br><span class="line"><span class="comment">     * accessTokenValiditySeconds：access_token的有效时间</span></span><br><span class="line"><span class="comment">     * refreshTokenValiditySeconds：refresh_token的有效时间</span></span><br><span class="line"><span class="comment">     * redirectUris：授权之后的跳转页面，注意必须是https的</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(ClientDetailsServiceConfigurer clients)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        clients.inMemory()</span><br><span class="line">                <span class="comment">// code码授权 authorization_code 配置示例</span></span><br><span class="line">                .withClient(<span class="string">&quot;wx&quot;</span>)</span><br><span class="line">                .secret(passwordEncoder.encode(<span class="string">&quot;wx-secret&quot;</span>))</span><br><span class="line">                .scopes(<span class="string">&quot;read&quot;</span>, <span class="string">&quot;write&quot;</span>)</span><br><span class="line">                .authorizedGrantTypes(<span class="string">&quot;authorization_code&quot;</span>)</span><br><span class="line">                .accessTokenValiditySeconds(<span class="number">7200</span>)</span><br><span class="line">                .refreshTokenValiditySeconds(<span class="number">72000</span>)</span><br><span class="line">                .redirectUris(<span class="string">&quot;https://www.baidu.com&quot;</span>);</span><br><span class="line"></span><br><span class="line">                <span class="comment">// 静默授权 implicit 配置示例</span></span><br><span class="line">                <span class="comment">// .and()</span></span><br><span class="line">                <span class="comment">// .withClient(&quot;qq&quot;)</span></span><br><span class="line">                <span class="comment">// .secret(passwordEncoder.encode(&quot;qq-secret&quot;))</span></span><br><span class="line">                <span class="comment">// .scopes(&quot;read&quot;)</span></span><br><span class="line">                <span class="comment">// .authorizedGrantTypes(&quot;implicit&quot;)</span></span><br><span class="line">                <span class="comment">// .accessTokenValiditySeconds(3600)</span></span><br><span class="line">                <span class="comment">// .redirectUris(&quot;https://www.baidu.com&quot;)</span></span><br><span class="line"></span><br><span class="line">                <span class="comment">// 密码授权 password 配置示例</span></span><br><span class="line">                <span class="comment">// .and()</span></span><br><span class="line">                <span class="comment">// .withClient(&quot;apple&quot;)</span></span><br><span class="line">                <span class="comment">// .secret(passwordEncoder.encode(&quot;apple-secret&quot;))</span></span><br><span class="line">                <span class="comment">// .scopes(&quot;readOnly&quot;)</span></span><br><span class="line">                <span class="comment">// .authorizedGrantTypes(&quot;password&quot;)</span></span><br><span class="line">                <span class="comment">// .accessTokenValiditySeconds(7200)</span></span><br><span class="line"></span><br><span class="line">                <span class="comment">// 客户端授权 client_credentials 配置示例</span></span><br><span class="line">                <span class="comment">// .and()</span></span><br><span class="line">                <span class="comment">// .withClient(&quot;web&quot;)</span></span><br><span class="line">                <span class="comment">// .secret(passwordEncoder.encode(&quot;web-secret&quot;))</span></span><br><span class="line">                <span class="comment">// .scopes(&quot;readOnly&quot;)</span></span><br><span class="line">                <span class="comment">// .authorizedGrantTypes(&quot;client_credentials&quot;)</span></span><br><span class="line">                <span class="comment">// .accessTokenValiditySeconds(300);</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 将授权信息暴露</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(AuthorizationServerEndpointsConfigurer endpoints)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        endpoints</span><br><span class="line">                <span class="comment">// 暴露redis进行保存，自动保存</span></span><br><span class="line">                .tokenStore(tokenStore());</span><br><span class="line"></span><br><span class="line">                <span class="comment">// 使用password授权模式，暴露给AuthenticationManager</span></span><br><span class="line">                <span class="comment">// .authenticationManager(authenticationManager);</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="5-2静默授权"><a href="#5-2静默授权" class="headerlink" title="5.2静默授权"></a>5.2静默授权</h3><ul>
<li>请求示例：<a target="_blank" rel="noopener" href="http://localhost:9999/oauth/authorize?response_type=token&amp;client_id=qq&amp;redirect_uri=https://www.baidu.com&amp;state=momo">http://localhost:9999/oauth/authorize?response_type=token&amp;client_id=qq&amp;redirect_uri=https://www.baidu.com&amp;state=momo</a></li>
<li>结果示例：<a target="_blank" rel="noopener" href="https://www.baidu.com/#access_token=83b6a9de-ca07-4a09-a8d3-c297b582fbf4&amp;token_type=bearer&amp;state=momo&amp;expires_in=3599&amp;scope=read">https://www.baidu.com/#access_token=83b6a9de-ca07-4a09-a8d3-c297b582fbf4&amp;token_type=bearer&amp;state=momo&amp;expires_in=3599&amp;scope=read</a></li>
<li><code>注意：直接返回token了</code></li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">AuthorizationServerConfiguration</span> <span class="keyword">extends</span> <span class="title class_">AuthorizationServerConfigurerAdapter</span> &#123;</span><br><span class="line">	..........</span><br><span class="line">        </span><br><span class="line">    <span class="comment">// 静默授权 implicit 配置示例</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(ClientDetailsServiceConfigurer clients)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        clients.inMemory()</span><br><span class="line">                .withClient(<span class="string">&quot;qq&quot;</span>)</span><br><span class="line">                .secret(passwordEncoder.encode(<span class="string">&quot;qq-secret&quot;</span>))</span><br><span class="line">                .scopes(<span class="string">&quot;read&quot;</span>)</span><br><span class="line">                .authorizedGrantTypes(<span class="string">&quot;implicit&quot;</span>)</span><br><span class="line">                .accessTokenValiditySeconds(<span class="number">3600</span>)</span><br><span class="line">                .redirectUris(<span class="string">&quot;https://www.baidu.com&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    .............</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="5-3密码授权"><a href="#5-3密码授权" class="headerlink" title="5.3密码授权"></a>5.3密码授权</h3><blockquote>
<ol>
<li>需要在继承<code>WebSecurityConfigurerAdapter</code>的配置类中重写并注入<code>AuthenticationManager</code></li>
<li>不需要访问登录页面，直接<code>POST</code>请求即可获取token</li>
<li>请求示例：<a target="_blank" rel="noopener" href="http://localhost:9999/oauth/token?grant_type=password&amp;username=admin&amp;password=admin">http://localhost:9999/oauth/token?grant_type=password&amp;username=admin&amp;password=admin</a></li>
<li>注意：需要在<code>Authorization</code>中选<code>Basic Auth</code> ，值为下面配置的客户端账号</li>
</ol>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">AuthorizationServerConfiguration</span> <span class="keyword">extends</span> <span class="title class_">AuthorizationServerConfigurerAdapter</span> &#123;</span><br><span class="line">	..........</span><br><span class="line">        </span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 使用password授权模式，注入AuthenticationManager，然后在端点暴露</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    <span class="keyword">private</span> AuthenticationManager authenticationManager;</span><br><span class="line">    </span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 密码授权 password 配置示例</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(ClientDetailsServiceConfigurer clients)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        clients.inMemory()</span><br><span class="line">                .withClient(<span class="string">&quot;apple&quot;</span>)</span><br><span class="line">                .secret(passwordEncoder.encode(<span class="string">&quot;apple-secret&quot;</span>))</span><br><span class="line">                .scopes(<span class="string">&quot;readOnly&quot;</span>)</span><br><span class="line">                .authorizedGrantTypes(<span class="string">&quot;password&quot;</span>)</span><br><span class="line">                .accessTokenValiditySeconds(<span class="number">7200</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 使用password授权模式，暴露给AuthenticationManager</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(AuthorizationServerEndpointsConfigurer endpoints)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        endpoints</span><br><span class="line">                <span class="comment">// 暴露redis进行保存，自动保存</span></span><br><span class="line">                .tokenStore(tokenStore())</span><br><span class="line"></span><br><span class="line">                <span class="comment">// 使用password授权模式，暴露给AuthenticationManager</span></span><br><span class="line">                .authenticationManager(authenticationManager);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    .............</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="5-3客户端授权"><a href="#5-3客户端授权" class="headerlink" title="5.3客户端授权"></a>5.3客户端授权</h3><ul>
<li>请求示例：<a target="_blank" rel="noopener" href="http://localhost:9999/oauth/token?grant_type=client_credentials">http://localhost:9999/oauth/token?grant_type=client_credentials</a></li>
<li>注意：需要在<code>Authorization</code>中选<code>Basic Auth</code> ，值为下面配置的客户端账号</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">AuthorizationServerConfiguration</span> <span class="keyword">extends</span> <span class="title class_">AuthorizationServerConfigurerAdapter</span> &#123;</span><br><span class="line">	..........</span><br><span class="line">        </span><br><span class="line">    <span class="comment">// 客户端授权 client_credentials 配置示例</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(ClientDetailsServiceConfigurer clients)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        clients.inMemory()</span><br><span class="line">                </span><br><span class="line">                .withClient(<span class="string">&quot;web&quot;</span>)</span><br><span class="line">                .secret(passwordEncoder.encode(<span class="string">&quot;web-secret&quot;</span>))</span><br><span class="line">                .scopes(<span class="string">&quot;readOnly&quot;</span>)</span><br><span class="line">                .authorizedGrantTypes(<span class="string">&quot;client_credentials&quot;</span>)</span><br><span class="line">                .accessTokenValiditySeconds(<span class="number">300</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    .............</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="6、自定义用户登录"><a href="#6、自定义用户登录" class="headerlink" title="6、自定义用户登录"></a>6、自定义用户登录</h2><h3 id="6-1实现UserDetailsService接口"><a href="#6-1实现UserDetailsService接口" class="headerlink" title="6.1实现UserDetailsService接口"></a>6.1实现UserDetailsService接口</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> org.springframework.security.core.authority.SimpleGrantedAuthority;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.core.userdetails.User;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.core.userdetails.UserDetails;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.core.userdetails.UserDetailsService;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.core.userdetails.UsernameNotFoundException;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.crypto.password.PasswordEncoder;</span><br><span class="line"><span class="keyword">import</span> org.springframework.stereotype.Service;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.context.request.RequestContextHolder;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.context.request.ServletRequestAttributes;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.annotation.Resource;</span><br><span class="line"><span class="keyword">import</span> javax.servlet.http.HttpServletRequest;</span><br><span class="line"><span class="keyword">import</span> java.util.ArrayList;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 自定义登录</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Service</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">UserDetailServiceImpl</span> <span class="keyword">implements</span> <span class="title class_">UserDetailsService</span> &#123;</span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    <span class="keyword">private</span> PasswordEncoder passwordEncoder;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 可以在此处继承数据来查询用户的账号，密码，权限等</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> UserDetails <span class="title function_">loadUserByUsername</span><span class="params">(String username)</span> <span class="keyword">throws</span> UsernameNotFoundException &#123;</span><br><span class="line">        <span class="comment">// 如何获取请求信息</span></span><br><span class="line">        <span class="type">ServletRequestAttributes</span> <span class="variable">requestAttributes</span> <span class="operator">=</span> (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();</span><br><span class="line">        HttpServletRequest request;</span><br><span class="line">        <span class="keyword">if</span> (requestAttributes != <span class="literal">null</span>) &#123;</span><br><span class="line">            request = requestAttributes.getRequest();</span><br><span class="line">            <span class="type">String</span> <span class="variable">header</span> <span class="operator">=</span> request.getHeader(<span class="string">&quot;Authorization&quot;</span>);</span><br><span class="line">            System.out.println(header);</span><br><span class="line">        &#125;</span><br><span class="line">s</span><br><span class="line">        <span class="comment">// 模拟一个用户，真实应该集成数据库查询获得</span></span><br><span class="line">        ArrayList&lt;SimpleGrantedAuthority&gt; adminAuthorities = <span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;&gt;();</span><br><span class="line">        adminAuthorities.add(<span class="keyword">new</span> <span class="title class_">SimpleGrantedAuthority</span>(<span class="string">&quot;sys:add&quot;</span>));</span><br><span class="line">        adminAuthorities.add(<span class="keyword">new</span> <span class="title class_">SimpleGrantedAuthority</span>(<span class="string">&quot;sys:delete&quot;</span>));</span><br><span class="line">        adminAuthorities.add(<span class="keyword">new</span> <span class="title class_">SimpleGrantedAuthority</span>(<span class="string">&quot;sys:update&quot;</span>));</span><br><span class="line">        adminAuthorities.add(<span class="keyword">new</span> <span class="title class_">SimpleGrantedAuthority</span>(<span class="string">&quot;sys:select&quot;</span>));</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">User</span>(<span class="string">&quot;admin&quot;</span>, passwordEncoder.encode(<span class="string">&quot;admin&quot;</span>), adminAuthorities);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="6-2配置WebSecurityConfigurerAdapter继承类"><a href="#6-2配置WebSecurityConfigurerAdapter继承类" class="headerlink" title="6.2配置WebSecurityConfigurerAdapter继承类"></a>6.2配置WebSecurityConfigurerAdapter继承类</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">WebSecurityConfiguration</span> <span class="keyword">extends</span> <span class="title class_">WebSecurityConfigurerAdapter</span> &#123;</span><br><span class="line">    ............</span><br><span class="line">    </span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    <span class="keyword">private</span> UserDetailServiceImpl userDetailService;</span><br><span class="line">    </span><br><span class="line">    </span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 配置用户和权限</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(AuthenticationManagerBuilder auth)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">		<span class="comment">//        auth.inMemoryAuthentication()</span></span><br><span class="line">		<span class="comment">//                .withUser(&quot;admin&quot;)</span></span><br><span class="line">		<span class="comment">//                .password(passwordEncoder.encode(&quot;admin&quot;))</span></span><br><span class="line">		<span class="comment">//                .roles(&quot;ADMIN&quot;)</span></span><br><span class="line">		<span class="comment">//                .authorities(&quot;sys:add&quot;, &quot;sys:delete&quot;, &quot;sys:update&quot;, &quot;sys:select&quot;)；</span></span><br><span class="line">        auth.userDetailsService(userDetailService);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<h2 id="7、资源服务器"><a href="#7、资源服务器" class="headerlink" title="7、资源服务器"></a>7、资源服务器</h2><blockquote>
<p>当变成资源服务器后，可以跳过登录，直接带token就可以访问（请求头Authorization，值为Bearer xxxxxxxxxxxxxx）</p>
<p>Security 的权限同样作用在token上</p>
<p><code>注意如果开启方法权限校验，需要在主启动类上加上@EnableGlobalMethodSecurity(prePostEnabled = true)</code></p>
</blockquote>
<p>在主启动类添加注解：<code>@EnableResourceServer</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@SpringBootApplication</span></span><br><span class="line"><span class="meta">@EnableAuthorizationServer</span> <span class="comment">// 标识为授权服务器</span></span><br><span class="line"><span class="meta">@EnableResourceServer</span> <span class="comment">// 开启资源服务器</span></span><br><span class="line"><span class="meta">@EnableGlobalMethodSecurity(prePostEnabled = true)</span> <span class="comment">// 开启方法权限校验</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MomoOauth2Application</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        SpringApplication.run(MomoOauth2Application.class, args);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="8、受保护的资源"><a href="#8、受保护的资源" class="headerlink" title="8、受保护的资源"></a>8、受保护的资源</h2><blockquote>
<p>简单理解就是微服务群中的资源服务器，访问需要带token</p>
<p><code>（瓶颈问题，压力全在授权服务器了，所以仅测试使用）</code></p>
</blockquote>
<h3 id="8-1授权服务器提供接口"><a href="#8-1授权服务器提供接口" class="headerlink" title="8.1授权服务器提供接口"></a>8.1授权服务器提供接口</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">UserController</span> &#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     *  获取用户信息</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@GetMapping(&quot;/getUserInfo&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> Object <span class="title function_">getUserInfo</span><span class="params">(Principal principal)</span> &#123;</span><br><span class="line">        System.out.println(principal);</span><br><span class="line">        <span class="keyword">return</span> principal;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="8-2资源服务器配置"><a href="#8-2资源服务器配置" class="headerlink" title="8.2资源服务器配置"></a>8.2资源服务器配置</h3><figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">security:</span></span><br><span class="line">  <span class="attr">oauth2:</span></span><br><span class="line">    <span class="attr">resource:</span></span><br><span class="line">      <span class="comment"># 用于验证token是不是授权服务器颁发的</span></span><br><span class="line">      <span class="attr">user-info-uri:</span> <span class="string">http://localhost:9999/getUserInfo</span></span><br></pre></td></tr></table></figure>
<h2 id="9、JWT-token"><a href="#9、JWT-token" class="headerlink" title="9、JWT token"></a>9、JWT token</h2><h3 id="9-1对称加密-token"><a href="#9-1对称加密-token" class="headerlink" title="9.1对称加密 token"></a>9.1对称加密 token</h3><h4 id="1-授权服务器配置"><a href="#1-授权服务器配置" class="headerlink" title="1.授权服务器配置"></a>1.授权服务器配置</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Bean;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Configuration;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.redis.connection.RedisConnectionFactory;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.authentication.AuthenticationManager;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.crypto.password.PasswordEncoder;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.oauth2.provider.token.TokenStore;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.oauth2.provider.token.store.JwtTokenStore;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.annotation.Resource;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">AuthorizationServerJWTConfiguration</span> <span class="keyword">extends</span> <span class="title class_">AuthorizationServerConfigurerAdapter</span> &#123;</span><br><span class="line">    </span><br><span class="line">    .......省略.......</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 用于oauth保存信息（自动保存）</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> TokenStore <span class="title function_">tokenStore</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">JwtTokenStore</span>(jwtAccessTokenConverter());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * JWT token转换器</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> JwtAccessTokenConverter <span class="title function_">jwtAccessTokenConverter</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">JwtAccessTokenConverter</span> <span class="variable">jwtAccessTokenConverter</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">JwtAccessTokenConverter</span>();</span><br><span class="line">        <span class="comment">// 需要一个签名密钥，是对称加密，注意密钥不应该保存在代码里面，下面仅测试</span></span><br><span class="line">        jwtAccessTokenConverter.setSigningKey(<span class="string">&quot;momo-oauth2-sign-key&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> jwtAccessTokenConverter;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 客户端配置，可配置多个</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(ClientDetailsServiceConfigurer clients)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        clients.inMemory()</span><br><span class="line">                <span class="comment">// code码授权 authorization_code 配置示例</span></span><br><span class="line">                .withClient(<span class="string">&quot;wx&quot;</span>)</span><br><span class="line">                .secret(passwordEncoder.encode(<span class="string">&quot;wx-secret&quot;</span>))</span><br><span class="line">                .scopes(<span class="string">&quot;read&quot;</span>, <span class="string">&quot;write&quot;</span>)</span><br><span class="line">                .authorizedGrantTypes(<span class="string">&quot;authorization_code&quot;</span>)</span><br><span class="line">                .accessTokenValiditySeconds(<span class="number">7200</span>)</span><br><span class="line">                .refreshTokenValiditySeconds(<span class="number">72000</span>)</span><br><span class="line">                .redirectUris(<span class="string">&quot;https://www.baidu.com&quot;</span>)</span><br><span class="line">            </span><br><span class="line">            .......省略.......</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 将授权信息暴露</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(AuthorizationServerEndpointsConfigurer endpoints)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        endpoints</span><br><span class="line">                <span class="comment">// 暴露给JwtAccessTokenConverter生成jwt token</span></span><br><span class="line">                .accessTokenConverter(jwtAccessTokenConverter())</span><br><span class="line"></span><br><span class="line">                <span class="comment">// 使用password授权模式，暴露给AuthenticationManager</span></span><br><span class="line">                .authenticationManager(authenticationManager);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="2资源服务器解析配置"><a href="#2资源服务器解析配置" class="headerlink" title="2资源服务器解析配置"></a>2资源服务器解析配置</h4><p>主动类</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@SpringBootApplication</span></span><br><span class="line"><span class="meta">@EnableResourceServer</span></span><br><span class="line"><span class="meta">@EnableGlobalMethodSecurity(prePostEnabled = true)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ConsumerApplication</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        SpringApplication.run(ConsumerApplication.class, args);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>配置类</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Bean;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Configuration;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.oauth2.provider.token.TokenStore;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.oauth2.provider.token.store.JwtTokenStore;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 资源服务器配置</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ResourceServerConfig</span> <span class="keyword">extends</span> <span class="title class_">ResourceServerConfigurerAdapter</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * token转换器，注意用同样的SigningKey</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> JwtAccessTokenConverter <span class="title function_">jwtAccessTokenConverter</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">JwtAccessTokenConverter</span> <span class="variable">jwtAccessTokenConverter</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">JwtAccessTokenConverter</span>();</span><br><span class="line">        jwtAccessTokenConverter.setSigningKey(<span class="string">&quot;momo-oauth2-sign-key&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> jwtAccessTokenConverter;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * tokenStore,用于oauth保存信息（自动保存）</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> TokenStore <span class="title function_">tokenStore</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">JwtTokenStore</span>(jwtAccessTokenConverter());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 资源服务器使用TokenStore</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(ResourceServerSecurityConfigurer resources)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        resources.tokenStore(tokenStore());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="9-2非对称加密-token"><a href="#9-2非对称加密-token" class="headerlink" title="9.2非对称加密 token"></a>9.2非对称加密 token</h3><blockquote>
<p>公钥加密，私钥解密</p>
</blockquote>
<h4 id="1-生成公钥和私钥"><a href="#1-生成公钥和私钥" class="headerlink" title="1.生成公钥和私钥"></a>1.生成公钥和私钥</h4><p>参考链接：<a target="_blank" rel="noopener" href="https://blog.csdn.net/qq_56042039/article/details/123584662">https://blog.csdn.net/qq_56042039/article/details/123584662</a></p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">keytool是java提供的密钥生成工具，帮助命令</span></span><br><span class="line">keytool -genkeypair --help</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash">使用git的bash来运行！！</span></span><br><span class="line">keytool -genkeypair -alias pri-key -keyalg RSA -keypass momo123456...  -storepass momo123456... -keystore pri-key.jks -validity 36500</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash">运行生保存公钥，.txt文件保存即可</span></span><br><span class="line">keytool -list -rfc --keystore pri-key.jks | openssl x509 -inform pem -pubkey</span><br></pre></td></tr></table></figure>
<h4 id="2-复制公钥到资源服务器，私钥到授权服务器"><a href="#2-复制公钥到资源服务器，私钥到授权服务器" class="headerlink" title="2.复制公钥到资源服务器，私钥到授权服务器"></a>2.复制公钥到资源服务器，私钥到授权服务器</h4><blockquote>
<p>注意：复制到resources文件下即可</p>
</blockquote>
<h4 id="3-授权服务器配置"><a href="#3-授权服务器配置" class="headerlink" title="3.授权服务器配置"></a>3.授权服务器配置</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">AuthorizationServerJWTConfiguration</span> <span class="keyword">extends</span> <span class="title class_">AuthorizationServerConfigurerAdapter</span> &#123;</span><br><span class="line">    </span><br><span class="line">    ........省略........</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * JWT token转换器</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> JwtAccessTokenConverter <span class="title function_">jwtAccessTokenConverter</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">JwtAccessTokenConverter</span> <span class="variable">jwtAccessTokenConverter</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">JwtAccessTokenConverter</span>();</span><br><span class="line">        <span class="comment">// 对称加密：需要一个签名密钥，注意密钥不应该保存在代码里面，下面仅测试</span></span><br><span class="line">        <span class="comment">// jwtAccessTokenConverter.setSigningKey(&quot;momo-oauth2-sign-key&quot;);</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 非对称加密：需要公钥和私钥，公钥保存在资源服务器，私钥保存在授权服务器</span></span><br><span class="line">        <span class="type">ClassPathResource</span> <span class="variable">resource</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ClassPathResource</span>(<span class="string">&quot;jwt-key.jks&quot;</span>);</span><br><span class="line">        <span class="comment">// 生成私钥时的密码</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">password</span> <span class="operator">=</span> <span class="string">&quot;momo123456...&quot;</span>;</span><br><span class="line">        <span class="type">KeyStoreKeyFactory</span> <span class="variable">keyStoreKeyFactory</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">KeyStoreKeyFactory</span>(resource, password.toCharArray());</span><br><span class="line">        <span class="type">KeyPair</span> <span class="variable">keyPair</span> <span class="operator">=</span> keyStoreKeyFactory.getKeyPair(<span class="string">&quot;jwt-key&quot;</span>);</span><br><span class="line">        jwtAccessTokenConverter.setKeyPair(keyPair);</span><br><span class="line">        <span class="keyword">return</span> jwtAccessTokenConverter;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    .........省略.......</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="4-资源服务器配置"><a href="#4-资源服务器配置" class="headerlink" title="4.资源服务器配置"></a>4.资源服务器配置</h4><p>引入依赖</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>cn.hutool<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>hutool-all<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>5.8.4<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> cn.hutool.core.io.FileUtil;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Bean;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Configuration;</span><br><span class="line"><span class="keyword">import</span> org.springframework.core.io.ClassPathResource;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.oauth2.provider.token.TokenStore;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.oauth2.provider.token.store.JwtTokenStore;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.nio.charset.Charset;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 资源服务器配置</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ResourceServerConfig</span> <span class="keyword">extends</span> <span class="title class_">ResourceServerConfigurerAdapter</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * token转换器，注意用同样的SigningKey</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> JwtAccessTokenConverter <span class="title function_">jwtAccessTokenConverter</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="type">JwtAccessTokenConverter</span> <span class="variable">jwtAccessTokenConverter</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">JwtAccessTokenConverter</span>();</span><br><span class="line">        <span class="comment">// 对称加密设置的密钥</span></span><br><span class="line">        <span class="comment">// jwtAccessTokenConverter.setSigningKey(&quot;momo-oauth2-sign-key&quot;);</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 非对称加密，资源服务器设置公钥</span></span><br><span class="line">        <span class="type">ClassPathResource</span> <span class="variable">classPathResource</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ClassPathResource</span>(<span class="string">&quot;pub.key&quot;</span>);</span><br><span class="line">        <span class="type">String</span> <span class="variable">publicKey</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            publicKey = FileUtil.readString(classPathResource.getFile(), Charset.defaultCharset());</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        jwtAccessTokenConverter.setVerifierKey(publicKey);</span><br><span class="line">        <span class="keyword">return</span> jwtAccessTokenConverter;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * tokenStore,用于oauth保存信息（自动保存）</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> TokenStore <span class="title function_">tokenStore</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">JwtTokenStore</span>(jwtAccessTokenConverter());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 资源服务器使用TokenStore</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(ResourceServerSecurityConfigurer resources)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        resources.tokenStore(tokenStore());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="10、JWT登出"><a href="#10、JWT登出" class="headerlink" title="10、JWT登出"></a>10、JWT登出</h2><blockquote>
<p>通过统一网关过滤器来实现</p>
</blockquote>
<h3 id="1建立网关"><a href="#1建立网关" class="headerlink" title="1建立网关"></a>1建立网关</h3><p>xml依赖</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.projectlombok<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>lombok<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.cloud<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-cloud-starter-gateway<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.cloud<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-cloud-starter-loadbalancer<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.alibaba.cloud<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-cloud-starter-alibaba-nacos-discovery<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-data-redis<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>cn.hutool<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>hutool-all<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>5.8.4<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>yml配置</p>
<figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">server:</span></span><br><span class="line">  <span class="attr">port:</span> <span class="number">11111</span></span><br><span class="line"></span><br><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">application:</span></span><br><span class="line">    <span class="attr">name:</span> <span class="string">momo-gateway-server</span></span><br><span class="line"></span><br><span class="line">  <span class="attr">cloud:</span></span><br><span class="line">    <span class="attr">nacos:</span></span><br><span class="line">      <span class="attr">discovery:</span></span><br><span class="line">        <span class="attr">server-addr:</span> <span class="string">$&#123;NACOS-HOST:182.61.55.41&#125;:$&#123;NACOS-PORT:8848&#125;</span></span><br><span class="line"></span><br><span class="line">    <span class="attr">gateway:</span></span><br><span class="line">      <span class="attr">discovery:</span></span><br><span class="line">        <span class="attr">locator:</span></span><br><span class="line">          <span class="attr">enabled:</span> <span class="literal">true</span> <span class="comment">#开启从注册中心动态创建路由的功能，利用微服务名进行路由</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">#        - id: momo-consumer   #路由的ID，没有固定规则但要求唯一，建议使用服务名</span></span><br><span class="line">  <span class="comment">#          uri: lb://momo-consumer #匹配后提供服务的路由地址</span></span><br><span class="line">  <span class="comment">#          predicates:</span></span><br><span class="line">  <span class="comment">#            #- Path=/oauth/token/** # 断言，路径相匹配的进行路由</span></span><br><span class="line">  <span class="comment">#            - Path=/**</span></span><br><span class="line">  <span class="comment">#          filters:</span></span><br><span class="line">  <span class="comment">#            # - LogFilter</span></span><br><span class="line"></span><br><span class="line">  <span class="attr">redis:</span></span><br><span class="line">    <span class="attr">host:</span> <span class="number">182.61</span><span class="number">.55</span><span class="number">.41</span></span><br><span class="line">    <span class="attr">port:</span> <span class="number">6379</span></span><br><span class="line">    <span class="attr">password:</span> <span class="string">momo123456...</span></span><br><span class="line">    <span class="attr">database:</span> <span class="number">0</span></span><br><span class="line">    <span class="attr">timeout:</span> <span class="number">10000</span></span><br></pre></td></tr></table></figure>
<h3 id="2网关配置"><a href="#2网关配置" class="headerlink" title="2网关配置"></a>2网关配置</h3><p><strong>对授权服务器配置网关服务</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> cn.hutool.json.JSONObject;</span><br><span class="line"><span class="keyword">import</span> cn.hutool.json.JSONUtil;</span><br><span class="line"><span class="keyword">import</span> lombok.extern.slf4j.Slf4j;</span><br><span class="line"><span class="keyword">import</span> org.springframework.cloud.gateway.route.RouteLocator;</span><br><span class="line"><span class="keyword">import</span> org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Bean;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Configuration;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.redis.core.StringRedisTemplate;</span><br><span class="line"><span class="keyword">import</span> org.springframework.util.StringUtils;</span><br><span class="line"><span class="keyword">import</span> reactor.core.publisher.Mono;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.annotation.Resource;</span><br><span class="line"><span class="keyword">import</span> java.time.Duration;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Slf4j</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">RouterConfig</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">OAUTH_KEY</span> <span class="operator">=</span> <span class="string">&quot;oauth:token:&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    <span class="keyword">private</span> StringRedisTemplate stringRedisTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> RouteLocator <span class="title function_">routeLocator</span><span class="params">(RouteLocatorBuilder routeLocatorBuilder)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> routeLocatorBuilder</span><br><span class="line">                .routes()</span><br><span class="line">                .route(<span class="string">&quot;momo-oauth2-server&quot;</span>, r -&gt; r.path(<span class="string">&quot;/oauth/**&quot;</span>, <span class="string">&quot;/loginOut&quot;</span>)</span><br><span class="line">                        .filters(f -&gt; f.modifyResponseBody(String.class, String.class, (exchange, s) -&gt; &#123;</span><br><span class="line">                            <span class="comment">// s 是responseBody，包含token和过期时间</span></span><br><span class="line">                            log.info(<span class="string">&quot;body:&#123;&#125;&quot;</span>, s);</span><br><span class="line"></span><br><span class="line">                            <span class="comment">// 将token设置到redis里面</span></span><br><span class="line">                            <span class="type">String</span> <span class="variable">path</span> <span class="operator">=</span> exchange.getRequest().getPath().value();</span><br><span class="line">                            <span class="keyword">if</span> (path.equalsIgnoreCase(<span class="string">&quot;/oauth/token&quot;</span>)) &#123;</span><br><span class="line">                                <span class="keyword">if</span> (StringUtils.hasText(s)) &#123;</span><br><span class="line">                                    <span class="type">JSONObject</span> <span class="variable">jsonObject</span> <span class="operator">=</span> JSONUtil.parseObj(s);</span><br><span class="line">                                    <span class="type">String</span> <span class="variable">accessToken</span> <span class="operator">=</span> jsonObject.getStr(<span class="string">&quot;access_token&quot;</span>);</span><br><span class="line">                                    <span class="keyword">if</span> (StringUtils.hasText(accessToken)) &#123;</span><br><span class="line">                                        <span class="type">Long</span> <span class="variable">expiresIn</span> <span class="operator">=</span> jsonObject.getLong(<span class="string">&quot;expires_in&quot;</span>);</span><br><span class="line">                                        stringRedisTemplate.opsForValue().set(OAUTH_KEY + accessToken, <span class="string">&quot;&quot;</span>, Duration.ofSeconds(expiresIn));</span><br><span class="line">                                    &#125;</span><br><span class="line">                                &#125;</span><br><span class="line">                            &#125;</span><br><span class="line"></span><br><span class="line">                            <span class="keyword">return</span> Mono.just(s);</span><br><span class="line">                        &#125;))</span><br><span class="line">                        .uri(<span class="string">&quot;lb://momo-oauth2-server&quot;</span>))</span><br><span class="line">                .build();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>配置一个全局过滤器，实现token鉴权</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.fasterxml.jackson.core.JsonProcessingException;</span><br><span class="line"><span class="keyword">import</span> com.fasterxml.jackson.databind.ObjectMapper;</span><br><span class="line"><span class="keyword">import</span> org.springframework.cloud.gateway.filter.GatewayFilterChain;</span><br><span class="line"><span class="keyword">import</span> org.springframework.cloud.gateway.filter.GlobalFilter;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Configuration;</span><br><span class="line"><span class="keyword">import</span> org.springframework.core.Ordered;</span><br><span class="line"><span class="keyword">import</span> org.springframework.core.io.buffer.DataBuffer;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.redis.core.StringRedisTemplate;</span><br><span class="line"><span class="keyword">import</span> org.springframework.http.HttpStatus;</span><br><span class="line"><span class="keyword">import</span> org.springframework.http.server.reactive.ServerHttpRequest;</span><br><span class="line"><span class="keyword">import</span> org.springframework.http.server.reactive.ServerHttpResponse;</span><br><span class="line"><span class="keyword">import</span> org.springframework.util.CollectionUtils;</span><br><span class="line"><span class="keyword">import</span> org.springframework.util.StringUtils;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.server.ServerWebExchange;</span><br><span class="line"><span class="keyword">import</span> reactor.core.publisher.Mono;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.annotation.Resource;</span><br><span class="line"><span class="keyword">import</span> java.util.Arrays;</span><br><span class="line"><span class="keyword">import</span> java.util.HashMap;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TokenCheckFilter</span> <span class="keyword">implements</span> <span class="title class_">GlobalFilter</span>, Ordered &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 接口白名单</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> List&lt;String&gt; AUTH_URL = Arrays.asList(<span class="string">&quot;/oauth/token&quot;</span>);</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">OAUTH_KEY</span> <span class="operator">=</span> <span class="string">&quot;oauth:token:&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    <span class="keyword">public</span> StringRedisTemplate stringRedisTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> Mono&lt;Void&gt; <span class="title function_">filter</span><span class="params">(ServerWebExchange exchange, GatewayFilterChain chain)</span> &#123;</span><br><span class="line">        <span class="type">ServerHttpRequest</span> <span class="variable">request</span> <span class="operator">=</span> exchange.getRequest();</span><br><span class="line">        <span class="type">String</span> <span class="variable">path</span> <span class="operator">=</span> request.getPath().value();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 白名单直接放行</span></span><br><span class="line">        <span class="keyword">if</span> (AUTH_URL.contains(path)) &#123;</span><br><span class="line">            <span class="keyword">return</span> chain.filter(exchange);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 查看redis里面的是否有token</span></span><br><span class="line">        List&lt;String&gt; tokenLists = request.getHeaders().get(<span class="string">&quot;Authorization&quot;</span>);</span><br><span class="line">        <span class="keyword">if</span> (!CollectionUtils.isEmpty(tokenLists)) &#123;</span><br><span class="line">            <span class="type">String</span> <span class="variable">token</span> <span class="operator">=</span> tokenLists.get(<span class="number">0</span>);</span><br><span class="line">            <span class="keyword">if</span> (StringUtils.hasText(token)) &#123;</span><br><span class="line">                <span class="comment">// 拿到真正的token，replaceAll区分大小写</span></span><br><span class="line">                <span class="type">String</span> <span class="variable">realToken</span> <span class="operator">=</span> token.replaceAll(<span class="string">&quot;Bearer &quot;</span>, <span class="string">&quot;&quot;</span>);</span><br><span class="line">                <span class="comment">// 看redis里面是否有token</span></span><br><span class="line">                <span class="type">Boolean</span> <span class="variable">hasKey</span> <span class="operator">=</span> stringRedisTemplate.hasKey(OAUTH_KEY + realToken);</span><br><span class="line">                <span class="keyword">if</span> (Boolean.TRUE.equals(hasKey)) &#123;</span><br><span class="line">                    <span class="keyword">return</span> chain.filter(exchange);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 未授权，返回401json给前台用户</span></span><br><span class="line">        <span class="type">ServerHttpResponse</span> <span class="variable">response</span> <span class="operator">=</span> exchange.getResponse();</span><br><span class="line">        response.getHeaders().add(<span class="string">&quot;content-type&quot;</span>, <span class="string">&quot;application/json;charset=utf-8&quot;</span>);</span><br><span class="line">        response.setStatusCode(HttpStatus.UNAUTHORIZED);</span><br><span class="line">        HashMap&lt;String, Object&gt; result = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;();</span><br><span class="line">        result.put(<span class="string">&quot;code&quot;</span>, <span class="number">401</span>);</span><br><span class="line">        result.put(<span class="string">&quot;msg&quot;</span>, <span class="string">&quot;用户未授权&quot;</span>);</span><br><span class="line">        <span class="type">ObjectMapper</span> <span class="variable">objectMapper</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ObjectMapper</span>();</span><br><span class="line">        <span class="type">byte</span>[] bytes = <span class="keyword">new</span> <span class="title class_">byte</span>[<span class="number">0</span>];</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            bytes = objectMapper.writeValueAsBytes(result);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (JsonProcessingException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="type">DataBuffer</span> <span class="variable">wrap</span> <span class="operator">=</span> response.bufferFactory().wrap(bytes);</span><br><span class="line">        <span class="keyword">return</span> response.writeWith(Mono.just(wrap));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">getOrder</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="3授权服务器添加登出接口"><a href="#3授权服务器添加登出接口" class="headerlink" title="3授权服务器添加登出接口"></a>3授权服务器添加登出接口</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> org.springframework.data.redis.core.StringRedisTemplate;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.core.context.SecurityContextHolder;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;</span><br><span class="line"><span class="keyword">import</span> org.springframework.util.StringUtils;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.GetMapping;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.RestController;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.annotation.Resource;</span><br><span class="line"></span><br><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">LogoutController</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">OAUTH_KEY</span> <span class="operator">=</span> <span class="string">&quot;oauth:token:&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    <span class="keyword">private</span> StringRedisTemplate stringRedisTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping(&quot;/loginOut&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">loginOut</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="comment">// 在请求头里面获取token</span></span><br><span class="line">        <span class="comment">// ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();</span></span><br><span class="line">        <span class="comment">// HttpServletRequest request = requestAttributes.getRequest();</span></span><br><span class="line">        <span class="comment">// String header = request.getHeader(&quot;Authorization&quot;);</span></span><br><span class="line">        <span class="comment">// String token = header.replaceAll(&quot;(?i)bearer &quot;, &quot;&quot;);</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 在SecurityContextHolder里面获取token</span></span><br><span class="line">        <span class="type">OAuth2AuthenticationDetails</span> <span class="variable">details</span> <span class="operator">=</span> (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();</span><br><span class="line">        <span class="type">String</span> <span class="variable">token</span> <span class="operator">=</span> details.getTokenValue();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (!StringUtils.hasText(token)) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="string">&quot;用户未登录!&quot;</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="type">Boolean</span> <span class="variable">hasKey</span> <span class="operator">=</span> stringRedisTemplate.hasKey(OAUTH_KEY + token);</span><br><span class="line">        <span class="keyword">if</span> (!Boolean.TRUE.equals(hasKey)) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="string">&quot;用户未登录!&quot;</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        stringRedisTemplate.delete(OAUTH_KEY + token);</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;退出登录成功！&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<ul>
<li>从网关拿token</li>
<li>从网关访问服务</li>
<li>从网关登出</li>
</ul>
</blockquote>
</article><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Java/">Java</a><a class="post-meta__tags" href="/tags/Security/">Security</a><a class="post-meta__tags" href="/tags/Oauth2/">Oauth2</a></div><div class="post_share"></div></div><nav class="pagination-post" id="pagination"><div class="next-post pull-full"><a href="/blog/java/02%20JWT%E5%B7%A5%E5%85%B7%E7%B1%BB/"><img class="next-cover" src= "" data-lazy-src="/images/jwt.jpeg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">JWT工具类</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/blog/java/00 Security 集成示例/" title="SpringSecurity 集成示例"><img class="cover" src= "" data-lazy-src="/images/spring-security.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2024-04-25</div><div class="title">SpringSecurity 集成示例</div></div></a></div><div><a href="/blog/java/00 SpringBoot自定义配置属性，filter，interceptor/" title="SpringBoot自定义配置，filter，interceptor"><img class="cover" src= "" data-lazy-src="/images/spring.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2024-04-21</div><div class="title">SpringBoot自定义配置，filter，interceptor</div></div></a></div><div><a href="/blog/java/01 SpringAMQP 快速使用/" title="SpringAMQP 快速使用"><img class="cover" src= "" data-lazy-src="/images/rabbitmq.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2024-03-30</div><div class="title">SpringAMQP 快速使用</div></div></a></div><div><a href="/blog/java/010 Redis 快速配置使用/" title="Redis 快速配置使用"><img class="cover" src= "" data-lazy-src="/images/redis.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2024-02-21</div><div class="title">Redis 快速配置使用</div></div></a></div><div><a href="/blog/java/02 JWT工具类/" title="JWT工具类"><img class="cover" src= "" data-lazy-src="/images/jwt.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2024-04-25</div><div class="title">JWT工具类</div></div></a></div><div><a href="/blog/java/100 SpringBoot允许跨域/" title="SpringBoot允许跨域"><img class="cover" src= "" data-lazy-src="/images/spring.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2024-04-21</div><div class="title">SpringBoot允许跨域</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">一切解释权归本咸鱼所有</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%B8%80%E3%80%81Spring-Security"><span class="toc-number">1.</span> <span class="toc-text">一、Spring Security</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81xml%E4%BE%9D%E8%B5%96"><span class="toc-number">1.1.</span> <span class="toc-text">1、xml依赖</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2%E3%80%81yml%E9%85%8D%E7%BD%AE"><span class="toc-number">1.2.</span> <span class="toc-text">2、yml配置</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3%E3%80%81Security%E9%85%8D%E7%BD%AE"><span class="toc-number">1.3.</span> <span class="toc-text">3、Security配置</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4%E3%80%81%E8%8E%B7%E5%8F%96%E7%94%A8%E6%88%B7%E4%BF%A1%E6%81%AF"><span class="toc-number">1.4.</span> <span class="toc-text">4、获取用户信息</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5%E3%80%81%E8%87%AA%E5%AE%9A%E4%B9%89%E7%99%BB%E5%BD%95%E6%88%90%E5%8A%9FHandler"><span class="toc-number">1.5.</span> <span class="toc-text">5、自定义登录成功Handler</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6%E3%80%81%E8%87%AA%E5%AE%9A%E4%B9%89%E7%99%BB%E5%BD%95%E5%A4%B1%E8%B4%A5Handler"><span class="toc-number">1.6.</span> <span class="toc-text">6、自定义登录失败Handler</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#7%E3%80%81%E8%87%AA%E5%AE%9A%E4%B9%89%E8%AE%BF%E9%97%AE%E8%A2%AB%E6%8B%92Handler"><span class="toc-number">1.7.</span> <span class="toc-text">7、自定义访问被拒Handler</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#8%E3%80%81%E6%96%B9%E6%B3%95%E7%BA%A7%E5%88%AB%E7%9A%84%E6%9D%83%E9%99%90%E6%8E%A7%E5%88%B6"><span class="toc-number">1.8.</span> <span class="toc-text">8、方法级别的权限控制</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#8-1%E4%B8%BB%E5%90%AF%E5%8A%A8%E7%B1%BB%E6%B7%BB%E5%8A%A0%E6%B3%A8%E8%A7%A3"><span class="toc-number">1.8.1.</span> <span class="toc-text">8.1主启动类添加注解</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#8-2%E6%96%B9%E6%B3%95%E7%BA%A7%E5%88%AB%E9%AA%8C%E8%AF%81"><span class="toc-number">1.8.2.</span> <span class="toc-text">8.2方法级别验证</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#9%E3%80%81%E8%87%AA%E5%AE%9A%E4%B9%89%E7%94%A8%E6%88%B7%E7%99%BB%E5%BD%95"><span class="toc-number">1.9.</span> <span class="toc-text">9、自定义用户登录</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#9-1%E5%AE%9E%E7%8E%B0UserDetailsService%E6%8E%A5%E5%8F%A3"><span class="toc-number">1.9.1.</span> <span class="toc-text">9.1实现UserDetailsService接口</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#9-2%E9%85%8D%E7%BD%AEWebSecurityConfigurerAdapter%E7%BB%A7%E6%89%BF%E7%B1%BB"><span class="toc-number">1.9.2.</span> <span class="toc-text">9.2配置WebSecurityConfigurerAdapter继承类</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#10%E3%80%81%E8%AE%B0%E4%BD%8F%E6%88%91"><span class="toc-number">1.10.</span> <span class="toc-text">10、记住我</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BA%8C%E3%80%81oauth2"><span class="toc-number">2.</span> <span class="toc-text">二、oauth2</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81xml%E4%BE%9D%E8%B5%96-1"><span class="toc-number">2.1.</span> <span class="toc-text">1、xml依赖</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2%E3%80%81yml%E9%85%8D%E7%BD%AE-1"><span class="toc-number">2.2.</span> <span class="toc-text">2、yml配置</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3%E3%80%81%E4%B8%BB%E5%90%AF%E5%8A%A8%E7%B1%BB"><span class="toc-number">2.3.</span> <span class="toc-text">3、主启动类</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4%E3%80%81%E9%85%8D%E7%BD%AESecurity"><span class="toc-number">2.4.</span> <span class="toc-text">4、配置Security</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#4-1%E5%85%AC%E7%94%A8%E7%9A%84bean%E9%85%8D%E7%BD%AE"><span class="toc-number">2.4.1.</span> <span class="toc-text">4.1公用的bean配置</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-2Security%E9%85%8D%E7%BD%AE"><span class="toc-number">2.4.2.</span> <span class="toc-text">4.2Security配置</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5%E3%80%81Oauth2%E9%85%8D%E7%BD%AE"><span class="toc-number">2.5.</span> <span class="toc-text">5、Oauth2配置</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#5-1code%E6%8E%88%E6%9D%83"><span class="toc-number">2.5.1.</span> <span class="toc-text">5.1code授权</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-2%E9%9D%99%E9%BB%98%E6%8E%88%E6%9D%83"><span class="toc-number">2.5.2.</span> <span class="toc-text">5.2静默授权</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-3%E5%AF%86%E7%A0%81%E6%8E%88%E6%9D%83"><span class="toc-number">2.5.3.</span> <span class="toc-text">5.3密码授权</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-3%E5%AE%A2%E6%88%B7%E7%AB%AF%E6%8E%88%E6%9D%83"><span class="toc-number">2.5.4.</span> <span class="toc-text">5.3客户端授权</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6%E3%80%81%E8%87%AA%E5%AE%9A%E4%B9%89%E7%94%A8%E6%88%B7%E7%99%BB%E5%BD%95"><span class="toc-number">2.6.</span> <span class="toc-text">6、自定义用户登录</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#6-1%E5%AE%9E%E7%8E%B0UserDetailsService%E6%8E%A5%E5%8F%A3"><span class="toc-number">2.6.1.</span> <span class="toc-text">6.1实现UserDetailsService接口</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-2%E9%85%8D%E7%BD%AEWebSecurityConfigurerAdapter%E7%BB%A7%E6%89%BF%E7%B1%BB"><span class="toc-number">2.6.2.</span> <span class="toc-text">6.2配置WebSecurityConfigurerAdapter继承类</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#7%E3%80%81%E8%B5%84%E6%BA%90%E6%9C%8D%E5%8A%A1%E5%99%A8"><span class="toc-number">2.7.</span> <span class="toc-text">7、资源服务器</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#8%E3%80%81%E5%8F%97%E4%BF%9D%E6%8A%A4%E7%9A%84%E8%B5%84%E6%BA%90"><span class="toc-number">2.8.</span> <span class="toc-text">8、受保护的资源</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#8-1%E6%8E%88%E6%9D%83%E6%9C%8D%E5%8A%A1%E5%99%A8%E6%8F%90%E4%BE%9B%E6%8E%A5%E5%8F%A3"><span class="toc-number">2.8.1.</span> <span class="toc-text">8.1授权服务器提供接口</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#8-2%E8%B5%84%E6%BA%90%E6%9C%8D%E5%8A%A1%E5%99%A8%E9%85%8D%E7%BD%AE"><span class="toc-number">2.8.2.</span> <span class="toc-text">8.2资源服务器配置</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#9%E3%80%81JWT-token"><span class="toc-number">2.9.</span> <span class="toc-text">9、JWT token</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#9-1%E5%AF%B9%E7%A7%B0%E5%8A%A0%E5%AF%86-token"><span class="toc-number">2.9.1.</span> <span class="toc-text">9.1对称加密 token</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-%E6%8E%88%E6%9D%83%E6%9C%8D%E5%8A%A1%E5%99%A8%E9%85%8D%E7%BD%AE"><span class="toc-number">2.9.1.1.</span> <span class="toc-text">1.授权服务器配置</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2%E8%B5%84%E6%BA%90%E6%9C%8D%E5%8A%A1%E5%99%A8%E8%A7%A3%E6%9E%90%E9%85%8D%E7%BD%AE"><span class="toc-number">2.9.1.2.</span> <span class="toc-text">2资源服务器解析配置</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#9-2%E9%9D%9E%E5%AF%B9%E7%A7%B0%E5%8A%A0%E5%AF%86-token"><span class="toc-number">2.9.2.</span> <span class="toc-text">9.2非对称加密 token</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-%E7%94%9F%E6%88%90%E5%85%AC%E9%92%A5%E5%92%8C%E7%A7%81%E9%92%A5"><span class="toc-number">2.9.2.1.</span> <span class="toc-text">1.生成公钥和私钥</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-%E5%A4%8D%E5%88%B6%E5%85%AC%E9%92%A5%E5%88%B0%E8%B5%84%E6%BA%90%E6%9C%8D%E5%8A%A1%E5%99%A8%EF%BC%8C%E7%A7%81%E9%92%A5%E5%88%B0%E6%8E%88%E6%9D%83%E6%9C%8D%E5%8A%A1%E5%99%A8"><span class="toc-number">2.9.2.2.</span> <span class="toc-text">2.复制公钥到资源服务器，私钥到授权服务器</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-%E6%8E%88%E6%9D%83%E6%9C%8D%E5%8A%A1%E5%99%A8%E9%85%8D%E7%BD%AE"><span class="toc-number">2.9.2.3.</span> <span class="toc-text">3.授权服务器配置</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4-%E8%B5%84%E6%BA%90%E6%9C%8D%E5%8A%A1%E5%99%A8%E9%85%8D%E7%BD%AE"><span class="toc-number">2.9.2.4.</span> <span class="toc-text">4.资源服务器配置</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#10%E3%80%81JWT%E7%99%BB%E5%87%BA"><span class="toc-number">2.10.</span> <span class="toc-text">10、JWT登出</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%E5%BB%BA%E7%AB%8B%E7%BD%91%E5%85%B3"><span class="toc-number">2.10.1.</span> <span class="toc-text">1建立网关</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%E7%BD%91%E5%85%B3%E9%85%8D%E7%BD%AE"><span class="toc-number">2.10.2.</span> <span class="toc-text">2网关配置</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%E6%8E%88%E6%9D%83%E6%9C%8D%E5%8A%A1%E5%99%A8%E6%B7%BB%E5%8A%A0%E7%99%BB%E5%87%BA%E6%8E%A5%E5%8F%A3"><span class="toc-number">2.10.3.</span> <span class="toc-text">3授权服务器添加登出接口</span></a></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/blog/java/01%20Spring%20Security%20&amp;%20oauth2/" title="Spring Security &amp; Oauth2"><img src= "" data-lazy-src="/images/spring-security.jpeg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Spring Security &amp; Oauth2"/></a><div class="content"><a class="title" href="/blog/java/01%20Spring%20Security%20&amp;%20oauth2/" title="Spring Security &amp; Oauth2">Spring Security &amp; Oauth2</a><time datetime="2024-04-25T07:24:45.000Z" title="发表于 2024-04-25 15:24:45">2024-04-25</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/java/02%20JWT%E5%B7%A5%E5%85%B7%E7%B1%BB/" title="JWT工具类"><img src= "" data-lazy-src="/images/jwt.jpeg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JWT工具类"/></a><div class="content"><a class="title" href="/blog/java/02%20JWT%E5%B7%A5%E5%85%B7%E7%B1%BB/" title="JWT工具类">JWT工具类</a><time datetime="2024-04-25T07:24:45.000Z" title="发表于 2024-04-25 15:24:45">2024-04-25</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/java/00%20Security%20%E9%9B%86%E6%88%90%E7%A4%BA%E4%BE%8B/" title="SpringSecurity 集成示例"><img src= "" data-lazy-src="/images/spring-security.jpeg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="SpringSecurity 集成示例"/></a><div class="content"><a class="title" href="/blog/java/00%20Security%20%E9%9B%86%E6%88%90%E7%A4%BA%E4%BE%8B/" title="SpringSecurity 集成示例">SpringSecurity 集成示例</a><time datetime="2024-04-25T07:24:43.000Z" title="发表于 2024-04-25 15:24:43">2024-04-25</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/java/101%20Mybatis-plus%E5%BF%AB%E9%80%9F%E9%9B%86%E6%88%90/" title="MybatisPlus 快速集成"><img src= "" data-lazy-src="/images/mybatis-plus.jpeg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="MybatisPlus 快速集成"/></a><div class="content"><a class="title" href="/blog/java/101%20Mybatis-plus%E5%BF%AB%E9%80%9F%E9%9B%86%E6%88%90/" title="MybatisPlus 快速集成">MybatisPlus 快速集成</a><time datetime="2024-04-21T07:39:43.000Z" title="发表于 2024-04-21 15:39:43">2024-04-21</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/java/10%20Mybatis%20%E5%BF%AB%E9%80%9F%E9%9B%86%E6%88%90/" title="Mybatis 快速集成"><img src= "" data-lazy-src="/images/mybaits.jpeg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Mybatis 快速集成"/></a><div class="content"><a class="title" href="/blog/java/10%20Mybatis%20%E5%BF%AB%E9%80%9F%E9%9B%86%E6%88%90/" title="Mybatis 快速集成">Mybatis 快速集成</a><time datetime="2024-04-21T07:24:43.000Z" title="发表于 2024-04-21 15:24:43">2024-04-21</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2024 By mowei</div><div class="footer_custom_text">海内存知已，天涯若比邻</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>if (document.getElementsByClassName('mermaid').length) {
  if (window.mermaidJsLoad) mermaid.init()
  else {
    getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(() => {
      window.mermaidJsLoad = true
      mermaid.initialize({
        theme: 'default',
      })
      true && mermaid.init()
    })
  }
}</script></div><div class="aplayer no-destroy" data-id="9385310356" data-server="netease" data-type="playlist" data-fixed="true" data-mini="true" data-listFolded="false" data-order="random" data-preload="none" data-autoplay="true" muted></div><canvas class="fireworks" mobile="false"></canvas><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/fireworks.min.js"></script><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/gh/metowolf/MetingJS@1.2/dist/Meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = [
  'title',
  '#config-diff',
  '#body-wrap',
  '#rightside-config-hide',
  '#rightside-config-show',
  '.js-pjax'
]

if (false) {
  pjaxSelectors.unshift('meta[property="og:image"]', 'meta[property="og:title"]', 'meta[property="og:url"]')
}

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.removeEventListener('scroll', window.tocScrollFn)
  window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // Analytics
  if (false) {
    MtaH5.pgv()
  }

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><script src="/live2d_models/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2d_models/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"jsonPath":"/live2d_models/assets/wanko.model.json"},"display":{"position":"left","width":100,"height":150,"hOffset":-10,"vOffset":40},"mobile":{"show":true},"react":{"opacity":0.7},"log":false});</script></body></html>